#include "StdAfx.h"
#include "../VSettings/vsettings.h"
#include "VTextCodecWIN1251.h"
#include "VSqlDatabase.h"

// VSqlDatabase ///////////////////////////////////////////////////////////////

//
VSqlDatabase::VSqlDatabase()
	:QSqlDatabase(*init().database())
{
}

//
bool VSqlDatabase::checkConnection()
{
	return setConnectionString(connectionString());
}

//
bool VSqlDatabase::VInit::setConnectionString(const QStringList &v_)
{
	QStringList v = v_;

	if (v.count() < 4)
		return false;
		
	m_database->setHostName(v[0].remove(QChar(' ')));
	m_database->setDatabaseName(v[1].remove(QChar(' ')));
	m_database->setUserName(v[2].remove(QChar(' ')));
	m_database->setPassword(v[3].remove(QChar(' ')));
	m_database->setConnectOptions("ISC_DPB_LC_CTYPE=WIN1251");

	VSettings settings("VSqlDatabase");
		settings.setValue("connectionString",v.join(";"));

	return m_database->open();
}

//
QStringList VSqlDatabase::VInit::connectionString() const
{
	VSettings settings("VSqlDatabase");
	QString ss = settings.value("connectionString").toString();
	QStringList sl = ss.split(';');

	if (sl.count() != 4)
		sl.clear();

	return sl;
}

//
VSqlDatabase::VInit::VInit()
{
	VTextCodecWIN1251::init();

	m_database = new QSqlDatabase;
	*m_database = QSqlDatabase::addDatabase("QIBASE");


/*
	VSettings settings("VSqlDatabase");
	m_database = new QSqlDatabase;
	*m_database = QSqlDatabase::addDatabase("QIBASE");

		m_database->setHostName(
			settings.value("hostName","localhost").toString()
		);
		settings.setValue("hostName",m_database->hostName());
		
		m_database->setDatabaseName(
			settings.value("databaseName","c:/Databases/VIDAR32.FDB").toString()
		);
		settings.setValue("databaseName",m_database->databaseName());

		//m_database.setHostName("vidar03");
		//m_database.setDatabaseName("d:/Vidar32/Databases/VIDAR32.FDB");
		
		m_database->setUserName("SYSDBA");
		m_database->setPassword("masterkey");
		m_database->setConnectOptions("ISC_DPB_LC_CTYPE=WIN1251");
		//m_database.setConnectOptions("ISC_DPB_LC_CTYPE=Latin1");
		//m_database.setConnectOptions("ISC_DPB_LC_CTYPE=UNICODE_FFS");
	
	//bool conn = 
	Q_ASSERT_X(m_database->open() == true, "VSqlDatabase","");
*/	
}	

//
QSqlDatabase *VSqlDatabase::VInit::database()
{
/*
	if (!m_database)
	{
		static QSqlDatabase db;
		return &db;
	}
*/
	Q_ASSERT(m_database != NULL);
	return m_database;
}

//
void VSqlDatabase::VInit::destroy()
{
	if (!m_database)
		return;

	m_database->close();
	delete m_database;
	m_database = NULL;
}
